package com.message.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.message.api.user.dao.AcLoginlogMapper;
import com.message.api.user.entity.AcLoginlog;
import com.message.api.user.service.AcLoginlogService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzl
 * @since 2021-05-20
 */
@Service
public class AcLoginlogServiceImpl extends ServiceImpl<AcLoginlogMapper, AcLoginlog> implements AcLoginlogService {

    @Override
    public List<AcLoginlog> list(AcLoginlog example) {
        return this.list(buildWrapper(example));
    }

    @Override
    public IPage<AcLoginlog> page(AcLoginlog example, IPage page) {
        return this.page(page, buildWrapper(example));
    }

    @Override
    public List<AcLoginlog> findByUsernameLastErrorlog(String username, Date successTime) {
        QueryWrapper<AcLoginlog> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AcLoginlog::getUsername, username)
                .gt(null != successTime, AcLoginlog::getLoginTime, successTime)
                .eq(AcLoginlog::getState, "1")
                .orderByDesc(AcLoginlog::getLoginTime);
        return super.list(wrapper);
    }

    @Override
    public AcLoginlog findByLastSuccessLog(String username) {
        return this.baseMapper.findLastSuccessByUsername(username);
    }

    @Override
    public Boolean toLogin(String username) {
        AcLoginlog       successlog = this.findByLastSuccessLog(username);
        List<AcLoginlog> errorlogs  = this.findByUsernameLastErrorlog(username, null != successlog ? successlog.getLoginTime() : null);
        if (null == errorlogs || errorlogs.size() < 5) {
            return true;
        } else {
            AcLoginlog acLoginlog = errorlogs.get(0);
            if (System.currentTimeMillis() - acLoginlog.getLoginTime().getTime() > 30 * 60 * 1000) {
                //最后一次登录失败记录在半小时之前
                return true;
            }
        }
        return false;
    }

    @Override
    public AcLoginlog addLog(Integer userid, String username, String result, String remark) {
        AcLoginlog acLoginlog = new AcLoginlog();
        acLoginlog.setUserid(userid);
        acLoginlog.setUsername(username);
        acLoginlog.setResult(result);
        acLoginlog.setRemark(remark);
        acLoginlog.setLoginTime(new Date());
        acLoginlog.setState("1");
        super.save(acLoginlog);
        return acLoginlog;
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<AcLoginlog> buildWrapper(AcLoginlog example) {
        QueryWrapper<AcLoginlog> wrapper = new QueryWrapper<>();
        return wrapper;
    }

}
